<?php

namespace App\Http\Controllers\Manage;

use App\Models\FamilyHistory;
use App\Models\Hospital;
use App\Models\MarriageHistory;
use App\Models\MedicalAuxiliary;
use App\Models\MedicalComplaint;
use App\Models\MedicalDiagnose;
use App\Models\MedicalDispose;
use App\Models\MedicalFollowUp;
use App\Models\MedicalHpi;
use App\Models\MedicalHpiSub;
use App\Models\MedicalPhysical;
use App\Models\PastHistory;
use App\Models\Patient;
use App\Models\PersonalHistory;
use App\Models\StMedicalNumber;
use App\Project\Printer\AuxiliaryPrinter;
use App\Project\Printer\ComplaintPrinter;
use App\Project\Printer\DiagnosePrinter;
use App\Project\Printer\DisposePrinter;
use App\Project\Printer\FamilyPrinter;
use App\Project\Printer\FollowUpPrinter;
use App\Project\Printer\HpiPrinter;
use App\Project\Printer\HpiSubPrinter;
use App\Project\Printer\MarriagePrinter;
use App\Project\Printer\PastPrinter;
use App\Project\Printer\PersonPrinter;
use App\Project\Printer\PhysicalPrinter;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Models\MedicalRecord;
use App\Http\Controllers\ApiController;
use App\Transformers\RecordTransformer;
use Illuminate\Support\Str;
use App\LogicService\Contracts\MedicalComplicationAuxiliaryLogicContract;
use App\LogicService\Contracts\MedicalComplicationLogicContract;
use App\LogicService\Contracts\MedicalComplicationPromptLogicContract;
use App\LogicService\Contracts\OphthalmologyFundusChangeLogicContract;
use App\LogicService\Contracts\OphthalmologyMacularEdemaLogicContract;
use App\LogicService\Contracts\OphthalmologyOrdinaryLogicContract;
use App\LogicService\Contracts\OphthalmologyRetinopathyLogicContract;

class PrintController extends ApiController
{
    /**
     * @var \App\Models\MedicalRecord
     */
    protected $record;

    protected $complication;

    protected $complicationAuxiliary;

    protected $complicationPrompt;

    private $ophthalmologyFundusChange;

    private $ophthalmologyOrdinary;

    private $ophthalmologyRetinopathy;

    private $ophthalmologyMacularEdema;

    //public $stMedicalNumberModel;

    protected $includes = [
        'first' => [
            'patient:print(true)', 'hospital', 'doctor', 'complaint', 'hpi', 'hpiSub', 'past', 'person',
            'marriage', 'family', 'physical', 'auxiliary:print(true)', 'diagnose', 'dispose', 'complication','numbers',
        ],

        'follow' => [
            'patient:print(true)', 'hospital', 'doctor', 'physical',
            'auxiliary:print(true)', 'diagnose', 'dispose', 'follow', 'hpiSub', 'complication','numbers'
        ]
    ];

    /**
     * PrintController constructor.
     * @param Request $request
     * @param MedicalComplicationLogicContract $complication
     * @param MedicalComplicationAuxiliaryLogicContract $complicationAuxiliary
     * @param MedicalComplicationPromptLogicContract $complicationPrompt
     * @param OphthalmologyFundusChangeLogicContract $ophthalmologyFundusChange
     * @param OphthalmologyOrdinaryLogicContract $ophthalmologyOrdinary
     * @param OphthalmologyRetinopathyLogicContract $ophthalmologyRetinopathy
     * @param OphthalmologyMacularEdemaLogicContract $ophthalmologyMacularEdema
     */
    public function __construct(Request $request, MedicalComplicationLogicContract $complication,
                                MedicalComplicationAuxiliaryLogicContract $complicationAuxiliary,
                                MedicalComplicationPromptLogicContract $complicationPrompt,
                                OphthalmologyFundusChangeLogicContract $ophthalmologyFundusChange,
                                OphthalmologyOrdinaryLogicContract $ophthalmologyOrdinary,
                                OphthalmologyRetinopathyLogicContract $ophthalmologyRetinopathy,
                                OphthalmologyMacularEdemaLogicContract $ophthalmologyMacularEdema)
    {
        parent::__construct();

        $this->record = MedicalRecord::withoutGlobalScope('hasBindDoctor')
            ->findOrFail($request->input('record_id'));
        $this->complication = $complication;
        $this->complicationAuxiliary = $complicationAuxiliary;
        $this->complicationPrompt = $complicationPrompt;
        $this->ophthalmologyFundusChange = $ophthalmologyFundusChange;
        $this->ophthalmologyOrdinary = $ophthalmologyOrdinary;
        $this->ophthalmologyRetinopathy = $ophthalmologyRetinopathy;
        $this->ophthalmologyMacularEdema = $ophthalmologyMacularEdema;

        //实例化
        //$this->stMedicalNumberModel = new StMedicalNumber();

        require_once(app_path('Project/helper.php'));
    }

    /**
     * 打印请求的方法 仅返回数据
     * @return \Illuminate\Http\JsonResponse
     */
    public function printer()
    {
        $this->fractal->parseIncludes($this->getPrintItems());

        return $this->item($this->record, new RecordTransformer());
    }

    /**
     * 打印的html 格式
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function show()
    {
        $items = $this->getPrintItems();

        $data = [];

        foreach ($items as $item) {
            if ($position = strpos($item, ':')) {
                $item = substr($item, 0, $position);
            }
            $data[$item] = $this->$item($this->record);

        }
        if(isset($data['numbers']['medical_number'])){
            $data['patient']['medical_number'] = $data['numbers']['medical_number'];
        }
        if (Str::startsWith(\Route::current()->uri(), 'api')) {
            $blade = 'api.print';
            \View::share('scene' ,  app('scene'));

        } else {
            $blade = 'manage.print';
        }

        return view($blade, array_merge(['record' => $this->record], $data));
    }

    /**
     * 报告的word导出
     */
    public function word()
    {
        $html = $this->show()->render();
    }

    protected function complication(MedicalRecord $record)
    {

        $result = array();
        $complication_result = $this->complication->getList($record->id);
        $complication_auxiliary_result = $this->complicationAuxiliary->getList($record->id);
        $prompt = $this->complicationPrompt->show($record->id);


        $auxiliary_string = '';
        $motor_nerve_conduction = '';
        $sensory_nerve_conduction = '';
        if ($complication_auxiliary_result) {
            foreach ($complication_auxiliary_result as $key => $value) {
                if($value['left_nature']||$value['right_nature']){
                    if($value['type']==1){
                        if (!empty($value['name'])) {
                            $motor_nerve_conduction .= $value['name'];
                        }
                        if ($value['left_nature'] == 1) {
                            $motor_nerve_conduction .= '左(-)，';
                        }
                        if ($value['left_nature'] == 2) {
                            $motor_nerve_conduction .= '左(+)，';
                        }

                        if ($value['right_nature'] == 1) {
                            $motor_nerve_conduction .= '右(-)，';
                        }
                        if ($value['right_nature'] == 2) {
                            $motor_nerve_conduction .= '右(+)，';
                        }
                        if (!is_null($value['remark']) && '' != $value['remark']) {
                            $motor_nerve_conduction .= '备注信息：'.$value['remark'].'，';
                        }
                    }else{
                        if (!empty($value['name'])) {
                            $sensory_nerve_conduction .= $value['name'];
                        }
                        if ($value['left_nature'] == 1) {
                            $sensory_nerve_conduction .= '左(-)，';
                        }
                        if ($value['left_nature'] == 2) {
                            $sensory_nerve_conduction .= '左(+)，';
                        }

                        if ($value['right_nature'] == 1) {
                            $sensory_nerve_conduction .= '右(-)，';
                        }
                        if ($value['right_nature'] == 2) {
                            $sensory_nerve_conduction .= '右(+)，';
                        }
                        if (!is_null($value['remark']) && '' != $value['remark']) {
                            $sensory_nerve_conduction .= '备注信息：'.$value['remark'].'，';
                        }
                    }


                }

            }
            if (!empty($motor_nerve_conduction)) {
                $motor_nerve_conduction = '运动神经传导：' . $motor_nerve_conduction;
            }
            if (!empty($sensory_nerve_conduction)) {
                $sensory_nerve_conduction = '感觉神经传导：' . $sensory_nerve_conduction;
            }
            $auxiliary_string = $motor_nerve_conduction . $sensory_nerve_conduction;
        }
        if (!empty($auxiliary_string)) {
            $auxiliary_string = '辅助检查：' . $auxiliary_string;
        }

        $result['auxiliary'] = $auxiliary_string;

        if ($prompt->prompt && !is_null($prompt->prompt) && '' != $prompt->prompt) {
            $result['prompt'] = '肌电图结果提示：' . $prompt->prompt . '，';
        } else {
            $result['prompt'] = '';
        }

        $clinical_symptoms_string = '';
        $specialty_string = '';
        if ($complication_result) {
            foreach ($complication_result as $key => $value) {
                if ($value['type'] == 1 && $value['nature'] != 0) {
                    if ($value['nature'] == 1) {
                        $clinical_symptoms_string .= $value['name'] . '(-)，';
                    } else {
                        $clinical_symptoms_string .= $value['name'] . '(+)，';
                    }
                    if (!is_null($value['remark']) && '' != $value['remark']) {
                        $clinical_symptoms_string .= '备注信息：' . $value['remark'] . '，';
                    }
                }

                if ($value['type'] == 2 && $value['nature'] != 0) {
                    if ($value['nature'] == 1) {
                        $specialty_string .= $value['name'] . '(-)，';
                    } else {
                        $specialty_string .= $value['name'] . '(+)，';
                    }
                    if (!is_null($value['remark']) && '' != $value['remark']) {
                        $specialty_string .= '备注信息：' . $value['remark'] . '，';
                    }
                }

            }

        }
        if (!empty($clinical_symptoms_string)) {
            $clinical_symptoms_string = '临床症状：' . $clinical_symptoms_string;
        }
        $result['clinical_symptoms'] = $clinical_symptoms_string;

        if (!empty($specialty_string)) {
            $specialty_string = '专科检查：' . $specialty_string;
        }
        $result['specialty'] = $specialty_string;


        $ordinary_data_result = $this->ophthalmologyOrdinary->getList($record->id);
        $fundus_change_data_result = $this->ophthalmologyFundusChange->getList($record->id);
        $retinopathy_data_result = $this->ophthalmologyRetinopathy->show($record->id);
        $macular_edema_data_result = $this->ophthalmologyMacularEdema->show($record->id);

        $result['ordinary'] = '';

        $ordinary_string = '';
        foreach ($ordinary_data_result as $key => $value) {

            if ($value['left'] != '' || $value['right'] != '') {
                if ($value['inspect_type'] == 1) {
                    $ordinary_string .= '视力（矫正）';
                } else {
                    switch ($value['routine_type']) {
                        case 1:
                            $ordinary_string .= '眼压(mmHg)';
                            break;
                        case 2:
                            $ordinary_string .= '眼前节';
                            break;
                        case 3:
                            $ordinary_string .= '晶状体(请描述混浊情况)';
                            break;
                        case 4:
                            $ordinary_string .= '玻璃体(请描述混浊情况)';
                            break;
                    }

                }
                if ($value['left'] != '') {
                    $ordinary_string .= '左(' . $value['left'] . ')，';
                }
                if ($value['right'] != '') {
                    $ordinary_string .= '右(' . $value['right'] . ')，';
                }

            }

        }
        if (!empty($ordinary_string)) {
            $ordinary_string = '眼科一般检查：' . $ordinary_string;
        }
        $result['ordinary'] = $ordinary_string;


        $result['fundus'] = '';
        $fundus_string = '';
        foreach ($fundus_change_data_result as $key => $value) {

            if ($value['status']) {

                switch ($value['project_type']) {
                    case 1:
                        $fundus_string .= '微血管瘤';

                        break;
                    case 2:
                        $fundus_string .= '出血';

                        break;
                    case 3:
                        $fundus_string .= '渗出';

                        break;
                    case 4:
                        $fundus_string .= '视网膜内微血管异常';

                        break;
                    case 5:
                        $fundus_string .= '视网膜静脉串珠样改变';

                        break;
                    case 6:
                        $fundus_string .= '新生血管';
                        break;
                }

                if ($value['status'] == 1) {
                    $fundus_string .= '（无），';

                } elseif ($value['status'] == 2) {
                    $fundus_string .= '（有），';

                }

                if ($value['left_quadrant'] != '') {
                    $fundus_string .= '左眼象限数(' . $value['left_quadrant'] . ')，';

                }

                if ($value['left_pathological_changes'] != '') {
                    $fundus_string .= '左眼病变数(' . $value['left_pathological_changes'] . ')，';

                }
                if ($value['right_quadrant'] != '') {
                    $fundus_string .= '右眼象限数(' . $value['right_quadrant'] . ')，';
                }
                if ($value['right_pathological_changes'] != '') {
                    $fundus_string .= '右眼病变数(' . $value['right_pathological_changes'] . ')，';

                }

            }

        }
        if (!empty($fundus_string)) {
            $fundus_string = '眼底改变：' . $fundus_string;
        }
        $result['fundus'] = $fundus_string;

        $result['retinopathy'] = '';

        if ($retinopathy_data_result) {
            if ($retinopathy_data_result['left'] > 1 || $retinopathy_data_result['right'] > 1) {

                $retinopathy_string = '';
                $retinopathy_string .= '糖尿病视网膜病变严重程度：';

                if ($retinopathy_data_result['left']) {

                    switch ($retinopathy_data_result['left']) {
                        case 1:
                            $retinopathy_string .= '左(无)，';
                            break;
                        case 2:
                            $retinopathy_string .= '左(轻度非增殖期)，';
                            break;
                        case 3:
                            $retinopathy_string .= '左(中度非增殖期)，';
                            break;
                        case 4:
                            $retinopathy_string .= '左(重度非增殖期)，';
                            break;
                        case 5:
                            $retinopathy_string .= '左(增殖期)，';
                            break;

                    }

                }
                if ($retinopathy_data_result['right']) {

                    switch ($retinopathy_data_result['right']) {
                        case 1:
                            $retinopathy_string .= '右(无)，';

                            break;
                        case 2:
                            $retinopathy_string .= '右(轻度非增殖期)，';

                            break;
                        case 3:
                            $retinopathy_string .= '右(中度非增殖期)，';

                            break;
                        case 4:
                            $retinopathy_string .= '右(重度非增殖期)，';

                            break;
                        case 5:
                            $retinopathy_string .= '右(增殖期)，';

                            break;

                    }

                }
                if ($retinopathy_data_result['remark']) {
                    $retinopathy_string .= '备注信息：' . $retinopathy_data_result['remark'] . '，';

                }
                $result['retinopathy'] = $retinopathy_string;
            }
        }

        $result['macular_edema'] = '';
        if ($macular_edema_data_result) {
            if ($macular_edema_data_result['left'] || $macular_edema_data_result['right']) {
                $macular_edema_string = '';

                $macular_edema_string .= '黄斑水肿：';
                if ($macular_edema_data_result['left']) {
                    if ($macular_edema_data_result['left'] == 1) {
                        $macular_edema_string .= '左(无)，';
                    } else {

                        $macular_edema_string .= '左(有)，';
                    }

                    if (isset($macular_edema_data_result['left_edema'])) {
                        $macular_edema_string .= '水肿边缘距离中心凹最短距离' . $macular_edema_data_result['left_edema'] . 'mm，';

                    }
                    if (isset($macular_edema_data_result['left_thickness'])) {
                        $macular_edema_string .= '黄斑区视网膜厚度' . $macular_edema_data_result['left_thickness'] . 'mm，';
                    }

                }
                if ($macular_edema_data_result['right']) {
                    if ($macular_edema_data_result['right'] == 1) {
                        $macular_edema_string .= '右(无)，';

                    } else {
                        $macular_edema_string .= '右(有)，';

                    }
                    if (isset($macular_edema_data_result['right_edema'])) {
                        $macular_edema_string .= '水肿边缘距离中心凹最短距离' . $macular_edema_data_result['right_edema'] . 'mm ，';

                    }
                    if (isset($macular_edema_data_result['right_thickness'])) {
                        $macular_edema_string .= '黄斑区视网膜厚度' . $macular_edema_data_result['right_thickness'] . 'mm ，';

                    }

                }
                if (!empty($macular_edema_data_result['remark'])) {
                    $macular_edema_string .= '备注信息' . $macular_edema_data_result['remark'] . '，';
                }
                $result['macular_edema'] = $macular_edema_string;
            }
        }

        if(!empty($result['macular_edema'])||!empty($result['retinopathy'])||!empty($result['fundus'])||!empty($result['ordinary'])||!empty($result['specialty'])||!empty($result['clinical_symptoms'])||!empty($result['prompt'])||!empty($result['auxiliary'])){
            $result['is_print'] = true;
        }else{
            $result['is_print'] = false;
        }

        return $result;
    }

    protected function patient(MedicalRecord $record)
    {
        $patient = Patient::where(['id' => $record->patient_id])->first([
            'name', 'sex', 'age', 'birthday', 'medical_number', 'diabetes_type'
        ]);
        //TODO 此处刘萌杰修改  将生日转化为年龄使用
        $patient['age'] = Carbon::parse($patient['birthday'])->age;
        return $patient;
    }

    protected function hospital(MedicalRecord $record)
    {
        if (is_numeric($record->hospital_id) && $record->hospital_id > 0) {
            return Hospital::where(['id' => $record->hospital_id])->first(['id', 'name']);
        }

        return null;
    }

    protected function doctor(MedicalRecord $record)
    {
        if (is_numeric($record->doctor_id) && $record->doctor_id > 0) {
            return User::where(['id' => $record->doctor_id])->first(['id', 'name']);
        }

        return null;
    }

    protected function complaint(MedicalRecord $record)
    {
        if ($past = MedicalComplaint::where(['record_id' => $record->id])->first()) {

            return ['print' => (new ComplaintPrinter($past))->printer(), 'model' => $past];
        }

        return null;
    }

    protected function hpi(MedicalRecord $record)
    {
        if ($hpi = MedicalHpi::where(['record_id' => $record->id])->select('id','diet','sport','adrenal_gland','adrenal_gland','adrenal_gland','normal','remark')->first()) {

            return ['print' => (new HpiPrinter($hpi))->printer(), 'model' => $hpi];
        }

        return null;
    }

    public function hpiSub(MedicalRecord $record)
    {
        $sub = MedicalHpiSub::where(['record_id' => $record->id])->get();

        if ($sub->count()) {
            return $sub->map(function (MedicalHpiSub $sub) {

                return ['print' => (new HpiSubPrinter($sub))->printer(), 'model' => $sub];
            })->all();
        }

        return null;
    }

    protected function past(MedicalRecord $record)
    {
        if ($past = PastHistory::where(['record_id' => $record->id])->first()) {

            return ['print' => (new PastPrinter($past))->printer(), 'model' => $past];
        }

        return null;
    }

    protected function person(MedicalRecord $record)
    {
        if ($person = PersonalHistory::where(['record_id' => $record->id])->first()) {

            return ['print' => (new PersonPrinter($person))->printer(), 'model' => $person];
        }

        return null;
    }

    protected function marriage(MedicalRecord $record)
    {
        if ($marriage = MarriageHistory::where(['record_id' => $record->id])->first()) {

            $patient = $record->patient;

            return ['print' => (new MarriagePrinter($marriage, $patient))->printer(), 'model' => $marriage];
        }

        return null;
    }

    protected function family(MedicalRecord $record)
    {
        if ($family = FamilyHistory::where(['record_id' => $record->id])->first()) {

            $result = ['print' => (new FamilyPrinter($family))->printer(), 'model' => $family];
            if (isset($result['print']['extend'])) {
                $extend = $result['print']['extend'];
                unset($result['print']['extend']);
                $result['print']['extend'] = $extend;
            }

            return $result;
        }

        return null;
    }

    protected function physical(MedicalRecord $record)
    {
        if ($physical = MedicalPhysical::where(['record_id' => $record->id])->first()) {

            return ['print' => (new PhysicalPrinter($physical, $record))->printer(), 'model' => $physical];
        }

        return null;
    }

    protected function auxiliary(MedicalRecord $record)
    {
        if ($auxiliary = (new MedicalAuxiliary())->printItems($record)) {

            $print = (new AuxiliaryPrinter($auxiliary, app('scene')))->printer();

            if (isset($print['ogtt'])) {

//                $print['ogtt'] = ['text' => $print['ogtt']];

                $titles = ['项目', '缩写', '0h', '0.5h', '1h', '2h', '3h'];

                $items = collect($auxiliary->ogtt)->only(['glu', 'ins', 'c-p'])->map(function ($result) {
                    return $result['results_n'];
                })->toArray();

                array_unshift($items['glu'], 'Glu(mmol/l)');
                array_unshift($items['glu'], '葡萄糖');
                array_unshift($items['ins'], 'Ins(uIU/ml)');
                array_unshift($items['ins'], '胰岛素');
                array_unshift($items['c-p'], 'C-P(ng/ml)');
                array_unshift($items['c-p'], '血浆C肽');

                $print['ogtt']['table'] = view('layouts.simple_table', ['titles' => $titles, 'items' => $items])->render();
            }

            return ['print' => collect($print)->groupBy('time')->toArray(), 'model' => $auxiliary];
        }

        return null;
    }

    protected function diagnose(MedicalRecord $record)
    {
        if ($diagnose = MedicalDiagnose::where(['record_id' => $record->id])->first()) {

            return ['print' => (new DiagnosePrinter($diagnose, $record))->printer(), 'model' => $diagnose];
        }

        return null;
    }

    protected function dispose(MedicalRecord $record)
    {
        if ($dispose = MedicalDispose::where(['record_id' => $record->id])->first()) {

            $print = (new DisposePrinter($dispose))->printer();

            $advise = isset($print['advise']) ? $print['advise'] : '';

            unset($print['advise']);

            return ['advise' => $advise, 'print' => $print, 'model' => $dispose];
        }

        return null;
    }

    protected function follow(MedicalRecord $record)
    {
        if ($follow = MedicalFollowUp::where(['record_id' => $record->id])->first()) {

            return ['print' => (new FollowUpPrinter($follow))->printer(), 'model' => $follow];
        }

        return null;
    }

    /**
     * 返回相关联的病案号的数据
     * @param MedicalRecord $record
     * @return array|null
     */
    protected function numbers(MedicalRecord $record)
    {
        if ($follow = StMedicalNumber::where(['patient_id'=>$record->patient_id,'hospital_id'=>$record->hospital_id])->first()) {
            return $follow;
        }


        return null;
    }

    protected function getPrintItems()
    {
        if ($this->record->isFirstVisit()) {
            return $this->includes['first'];
        }

        return $this->includes['follow'];
    }

}
